import datetime
import requests
from .models import Lecture
from config import YUQUE_TOKEN

api = "https://www.yuque.com/api/v2/repos/greatnju/lecture"

headers = {
    "User-Agent": "py",
    "Content-Type": "application/json",
    "X-Auth-Token": YUQUE_TOKEN,
}


def create_doc(data: Lecture):
    param = {"title": data.title, "body": data.markdown}

    response = requests.post(url=f"{api}/docs", headers=headers, params=param).json()

    return response["data"]["id"], response["data"]["slug"]


def del_doc(id):
    requests.delete(url=f"{api}/docs/{id}", headers=headers)


def move_toc(id, slug, date: datetime.date):
    # get toc list
    response = requests.get(f"{api}/toc", headers=headers).json()

    # find parent
    targetTitle = str(date)
    targetUuid = None
    lastDay = None
    lastUuid = None

    for x in response["data"]:
        # 不是分组节点，跳过
        if x["type"] != "TITLE":
            continue
        # 结束查找
        if x["title"] == "历史讲座":
            break
        # 有对应日期节点，直接插入
        if x["title"] == targetTitle:
            targetUuid = x["uuid"]
            break
        # 是日期分组标题，且不是对应日期
        if len(x["title"]) == 10:
            titleDay = datetime.datetime.strptime(x["title"], "%Y-%m-%d").date()
            titleUuid = x["uuid"]
            if lastDay is None or titleDay < date:
                lastDay = titleDay
                lastUuid = titleUuid
            else:
                break

    if targetUuid is None:
        # 创建日期分组节点，默认插入在目录头部
        param = {"action": "insert", "title": str(date), "type": "TITLE"}
        response = requests.put(url=f"{api}/toc", headers=headers, params=param).json()
        targetUuid = response["data"][0]["uuid"]
        # 移动到last后面
        param = {
            "action": "moveAfter",
            "node_uuid": targetUuid,
            "target_uuid": lastUuid,
        }
        response = requests.put(url=f"{api}/toc", headers=headers, params=param).json()

    # 插入到对应日期目录下
    param = {
        "action": "insert",
        "target_uuid": targetUuid,
        "doc_id": id,
        "url": slug,
        "type": "DOC",
    }

    response = requests.put(url=f"{api}/toc", headers=headers, params=param).json()

    return response


def upload(data):
    id, slug = create_doc(data)
    move_toc(id, slug, data.date)
    return id, slug
